package cn.openea.perpartner.common.auth.login;



import cn.openea.perpartner.common.auth.config.AuthConfig;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.common.auth.util.CookieUtil;
import cn.openea.perpartner.common.auth.exception.SsoException;
import cn.openea.perpartner.common.auth.util.SessionUtil;
import cn.openea.perpartner.common.redis.service.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


/**
 * @author Weird077
 * @description TODO
 * @date 2022-04-25 10:18
 */
@Service
public class LoginService {
    @Autowired
    private RedisCache redisCache;
    /**
     * 默认redis失效时间，1440min,24hour
     */
    private  int redisExpireMinute = 1440;
    private  int defaultExpireMinute = 30;
    public  int getRedisExpireMinute() {
        return redisExpireMinute;
    }

    /**
     * 设置redis失效时间
     * @param redisExpireMinute 30min
     */
    public  void setRedisExpireMinute(int redisExpireMinute) {
        if (redisExpireMinute < defaultExpireMinute) {
            redisExpireMinute = defaultExpireMinute;
        }
        this.redisExpireMinute = redisExpireMinute;
    }

    /**
     * app登录
     */
    public void login(String sessionId, LoginBody user) {
        String storeKey = SessionUtil.parseStoreKey(sessionId);
        if (storeKey == null) {
            throw new SsoException("parse storeKey Fail, sessionId:" + sessionId);
        }
        this.put(storeKey, user);
    }

    /**
     * web登录
     */
    public void login(HttpServletResponse response,String sessionId,LoginBody user,boolean ifRem) {
        String storeKey = SessionUtil.parseStoreKey(sessionId);
        if (storeKey == null) {
            throw new SsoException("parse storeKey Fail, sessionId:" + sessionId);
        }
        this.put(storeKey, user);
        CookieUtil.set(response, AuthConfig.SSO_SESSIONID, sessionId, ifRem);
    }

    /**
     * app logout
     */
    public void logout(String sessionId) {
        String storeKey = SessionUtil.parseStoreKey(sessionId);
        if (storeKey == null) {
            return;
        }
        this.remove(storeKey);
    }

    /**
     * app logout
     */
    public void logout(HttpServletRequest request) {
        this.logout(request.getHeader(AuthConfig.SSO_SESSIONID));
    }

    /**
     * web logout
     */
    public void logout(HttpServletRequest request,HttpServletResponse response) {
        String sessionId = CookieUtil.getValue(request, AuthConfig.SSO_SESSIONID);
        if (sessionId == null) {
            return;
        }
        String storeKey = SessionUtil.parseStoreKey(sessionId);
        if (storeKey != null) {
            this.remove(storeKey);
        }
        this.removeSessionIdByCookie(request,response);
    }
    
    /**
     * app校验用户是否登录
     */
    public LoginBody loginCheck(HttpServletRequest request) {
        return loginCheck(request.getHeader(AuthConfig.SSO_SESSIONID));
    }
    /**
     * web校验用户是否登录
     */
    public LoginBody loginCheck(HttpServletRequest request, HttpServletResponse response) {
        String sessionId = CookieUtil.getValue(request, AuthConfig.SSO_SESSIONID);
        LoginBody user = loginCheck(sessionId);
        if (user != null) {
            return user;
        }
        this.removeSessionIdByCookie(request, response);
        sessionId = request.getParameter(AuthConfig.SSO_SESSIONID);
        user = loginCheck(sessionId);
        if (user != null) {
            CookieUtil.set(response, AuthConfig.SSO_SESSIONID, sessionId, false);
            return user;
        }
        return null;
    }
    /**
     * 根据sessionId校验用户是否登录
     */
    public LoginBody loginCheck(String sessionId) {
        String storeKey = SessionUtil.parseStoreKey(sessionId);
        if (storeKey == null) {
            return null;
        }
        LoginBody user = this.get(storeKey);
        if (user != null) {
            String version = SessionUtil.parseVersion(sessionId);
            if (user.getVersion().equals(version)) {
                if ((System.currentTimeMillis() - user.getExpireFreshTime()) > user.getExpireMinute() / 2) {
                    user.setExpireFreshTime(System.currentTimeMillis());
                    this.put(storeKey, user);
                }
                return user;
            }
        }
        return null;
    }

    public  void removeSessionIdByCookie(HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.remove(request, response, AuthConfig.SSO_SESSIONID);
    }
    public  String getSessionIdByCookie(HttpServletRequest request) {
        return CookieUtil.getValue(request, AuthConfig.SSO_SESSIONID);
    }

    /**
     * 从缓存里获取登录对象
     */
    public LoginBody get(String key){
        Object obj = redisCache.getCacheObject(redisKey(key));
        return obj!=null? (LoginBody) obj :null;
    }

    /**
     * 删除缓存
     */
    public void remove(String key){
        redisCache.deleteObject(redisKey(key));
    }

    /**
     * 将登录对象放入redis缓存
     */
    public void put(String key, LoginBody user){redisCache.setCacheObject(redisKey(key),user,redisExpireMinute, TimeUnit.MINUTES);}

    /**
     * 格式化key
     */
    public  String redisKey(String key){return AuthConfig.SSO_SESSIONID.concat("=").concat(key);}

}
